package com.zky.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.zky.common.exception.BizCodeEnum;
import com.zky.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description 网关sentinel配置
 * @Author 张开源
 * @Date 2023/1/7 21:28
 * @Version 1.0
 **/
@Configuration
public class SentinelGateWayConfig {
    public SentinelGateWayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //网关限流就会调用此回调
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
                String jsonString = JSON.toJSONString(error);
                Mono<ServerResponse> responseMono = ServerResponse.ok().body(Mono.just(jsonString), String.class);
                return responseMono;
            }
        });
    }
}
